<template>
    <div class="demographic-2D-container">
        <canvas class="demographic-2D-canvas"></canvas>
    </div>
</template>

<script>
import ErrorEmote from '@/components/specialeffects/ErrorEmote.vue';
import { h, render } from 'vue';

export default {
    name: "Demographic2D",
    components: {},
    data() {
        return {
        }
    },
    computed: {},
    methods: {
        //加载失败
        loadError(error) {
            console.error(error);
            this.hasError = true;
            const view = this.$el.parentElement.querySelector(".demographic-2D-container");
            const errorIns = h(ErrorEmote);
            render(errorIns, view);
        },
        //加载人口统计数据文件
        async loadFile(url) {
            const res = await fetch(url);
            return res.text();
        },
        parseData(text) {
            if (!text) {
                return;
            }
            const data = [];
            const settings = { data };
            let max;
            let min;
            // 对每一行进行切分
            text.split('\n').forEach((line) => {
                // split the line by whitespace
                const parts = line.trim().split(/\s+/);
                if (parts.length === 2) {
                    // 长度为2的必定是键值对
                    settings[parts[0]] = parseFloat(parts[1]);
                } else if (parts.length > 2) {
                    // 长度超过2的肯定是网格数据
                    const values = parts.map((v) => {
                        const value = parseFloat(v);
                        if (value === settings.NODATA_value) {
                            return undefined;
                        }
                        max = Math.max(max === undefined ? value : max, value);
                        min = Math.min(min === undefined ? value : min, value);
                        return value;
                    });
                    data.push(values);
                }
            });
            return Object.assign(settings, { min, max });
        },
        drawData(file) {
            if (!file) {
                this.loadError("格式错误");
                return;
            }
            const { ncols, nrows, min, max, data } = file;
            if(!ncols){
                this.loadError("格式错误");
                return;
            }
            const range = max - min;
            const ctx = document.querySelector('.demographic-2D-canvas').getContext('2d');
            // 新建一个和网格数据尺寸相等的canvas
            ctx.canvas.width = ncols;
            ctx.canvas.height = nrows;
            // 但是以两倍大小绘制防止太小
            ctx.canvas.style.width = this.px(ncols * 2);
            ctx.canvas.style.height = this.px(nrows * 2);
            // 用黑灰色填充
            ctx.fillStyle = '#444';
            ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
            // 绘制数据点
            data.forEach((row, latNdx) => {
                row.forEach((value, lonNdx) => {
                    if (value === undefined) {
                        return;
                    }
                    const amount = (value - min) / range;
                    const hue = 1;
                    const saturation = 1;
                    const lightness = amount;
                    ctx.fillStyle = this.hsl(hue, saturation, lightness);
                    ctx.fillRect(lonNdx, latNdx, 1, 1);
                });
            });
        },

        px(v) {
            return `${v | 0}px`;
        },
        hsl(h, s, l) {
            return `hsl(${h * 360 | 0},${s * 100 | 0}%,${l * 100 | 0}%)`;
        },
    },
    created() {
        this.loadFile('/data/gpw_v4_basic_demographic_characteristics_rev10_a000_014mt_2010_cntm_1_deg.asc')
            .then(this.parseData)
            .then(this.drawData);
    },
    mounted() {
    },
}
</script>

<style scoped>
.demographic-2D-container {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
}
</style>